import Axios, { AxiosResponse, AxiosRequestConfig, AxiosError } from "axios";
// import router from "@/router";
// import Store from "@/store";
import errorCode from "./ErrorCode";
import { Toast } from "vant";
const startLoading = () => {
  // 开始加载
  Toast.loading({
    message: "加载中...",
    forbidClick: true,
  });
};
const endLoading = () => {
  // 结束加载
  Toast.clear();
};
let baseURL = "";
if (process.env.NODE_ENV == "development") {
  baseURL = "http://localhost:8083";
  console.log("development");
} else if (process.env.NODE_ENV == "production") {
  console.log("development");
}
const service = Axios.create({
  baseURL,
  timeout: 10000,
  responseType: "json",
});

/**
 * @description 请求发起前的拦截器
 */
service.interceptors.request.use(async (config: AxiosRequestConfig) => {
  startLoading();
  // 如果是获取token接口：
  // if (config.url === "/auth/oauth/token") {
  //   let userAccount = "";
  //   // 若存在username，则为登录情况，判断user-account
  //   if (config.params.username) {
  //     userAccount = config.params.username.includes("-")
  //       ? "ACCOUNT_USER"
  //       : "ADMIN_USER";
  //   } else {
  //     // 刷新token情况，通过用户信息email是否有值判断
  //     userAccount = Store.state.user.userDetail.email
  //       ? "ADMIN_USER"
  //       : "ACCOUNT_USER";
  //   }

  //   config.headers["User-Account"] = userAccount;
  //   config.headers.Authorization = "Basic ZmViczoxMjM0NTY=";
  // } else {
  //   // 如果保存有token，则取，否则不添加Authorization
  //   if (localStorage.vuex && JSON.parse(localStorage.vuex).user?.token) {
  //     const token = Store.state.user?.token;
  //     const tokenType = token.token_type;
  //     const accessToken = token.access_token;
  //     config.headers.Authorization = `${tokenType} ${accessToken}`;
  //   }
  // }
  return config;
});

/**
 * @description 响应收到后的拦截器
 */
service.interceptors.response.use(
  /** 请求有响应 */
  async (response: AxiosResponse) => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      const __text = errorCode(response);
      return Promise.reject(new Error(__text));
    }
  },
  /** 请求无响应 */
  (error: AxiosError) => {
    let __emsg: string = error.message || "";

    if (error.message) {
      __emsg = error.message;
    }

    if (error.response) {
      __emsg = error.response.data.message
        ? error.response.data.message
        : error.response.data.data;
    }
    // timeout
    if (__emsg.indexOf("timeout") >= 0) {
      __emsg = "timeout";
    }

    // if (error?.response?.status === 401) {
    //   if (router.currentRoute.value.path !== "/entry/login") {
    //     message.info("登录凭证已过期，请重新登录");
    //     router.push("/entry/login");
    //   }
    //   return Promise.reject(new Error("401"));
    // }
    endLoading();
    return Promise.reject(new Error(__emsg));
  }
);

export default service;
